package com.lianlianpay;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alipay.AliPay;
import com.lianlianpay.bean.QuickPayMentBean;
import com.seek.common.handler.SpringContextHolder;
import com.seek.inter.interdto.InterDtoCUser;
import com.seek.model.dto.ResultInfo;
import com.seek.model.entity.TLoanRepayment;
import com.seek.service.LoanRePayMentService;
import com.seek.service.LoanService;
import com.seek.util.CommonUtil;
import com.seek.util.ConstantsUtil;

public class LianLianWithhold {
	private static final Logger logger = LoggerFactory.getLogger(LianLianWithhold.class);
	private static LoanService  loanService = (LoanService)SpringContextHolder.getBean("loanService");
	private static LoanRePayMentService loanRePayMentService = (LoanRePayMentService)SpringContextHolder.getBean("loanRePayMentService");

	// 创建预支付订单
	public ResultInfo lianWithholdBefore(HttpServletRequest request, com.alibaba.fastjson.JSONObject reqJson) throws Exception{
		ResultInfo result= new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		Long loanId = reqJson.getLong("loanId");
		int type = CommonUtil.getIntValue(reqJson.getString("type")); // 1续借 2还款
		int payType = CommonUtil.getIntValue(reqJson.getString("payType")); // 1支付宝还款 2银行卡还款 3手工还款
//		int payMoney = CommonUtil.getIntValue(reqJson.getString("payMoney"));//还款金额：单位分
//		int latefee = CommonUtil.getIntValue(reqJson.getString("latefee"));//滞纳金：单位分
		String token = reqJson.getString("token");
		InterDtoCUser cust = com.seek.cache.CacheUtil.getCLoginCache(token);

		// 检查传入的参数
		if (companyId == null || companyId < 1 || loanId == null || loanId<1 || type<1 || type>2 || payType<1 || payType>3 || cust == null){
			result.setStatus(1);
			result.setMessage("参数错误，请检查");
			return result;
		}
		
		// 1 根据loanId取得订单信息
		String sql = "select id loanId, req_money reqMoney,ifnull((late_fee - off_latefee),0) lateFee,order_no orderNo from t_loan a where a.id=?";
		Map<String,Object> map = loanService.findOneMapBySql(sql, new Object[]{loanId});
		if (MapUtils.isEmpty(map)){
			result.setStatus(1);
			result.setMessage("参数错误，请检查");
			return result;
		}
		
		// 如果业务为还款，则校验还款总金额是否一致，如果业务为续借，则校验手续费和滞纳金是否一致
		int handleFee = 0;
		int latefee = 0;
		int payMoney = 0;
		if (type == 1){
			handleFee = loanService.getHandleFee(companyId, CommonUtil.getIntValue(map.get("reqMoney")));
			latefee = CommonUtil.getIntValue(map.get("lateFee"));//滞纳金
			payMoney = handleFee + latefee;
//			if (Math.abs(handleFee + lateFeeSys - payMoney)>1 || Math.abs(latefee - lateFeeSys)>1){
//				result.setStatus(2);
//				result.setMessage("续借金额与系统不一致，请检查");
//				return result;
//			}
		}else{
			latefee = CommonUtil.getIntValue(map.get("lateFee"));//滞纳金
			int reqMoney = CommonUtil.getIntValue(map.get("reqMoney"));//贷款金额
			payMoney = latefee + reqMoney;
//			if (Math.abs(reqMoney + lateFeeSys-payMoney)>1 || Math.abs(latefee-lateFeeSys)>1){
//				result.setStatus(2);
//				result.setMessage("还款金额与系统不一致，请检查");
//				return result;
//			}
		}
		
		TLoanRepayment loanRepayment = null;
		try{
			// 生成一条预支付订单
			loanRepayment = this.createRepayment(companyId, loanId, type, payType, payMoney, latefee);
			// 组合所需要的参数
			Map<String,Object> params = this.getParams(loanRepayment, cust, companyId, payMoney, handleFee);
			// 生成支付宝或连连支付的预支付订单
			QuickPayMentBean bean = null;
			if(payType == 2){
				bean = LianLianQuickPayMent.quickPayMent(params);
				result.setBody(bean);
			}else if(payType == 1){
				bean = AliPay.aliPay(params);
				 result.setBody(bean);
			}
			result.setStatus(0);
			result.setMessage("支付订单创建成功");
			return result;
		}catch(Exception e){
			// 如果出现异常，则预支付订单应该删除
			if (loanRepayment != null){
				sql = "delete from t_loan_repayment where id=?";
				loanRePayMentService.executeUpdate(sql);
			}
			logger.error(e.getMessage());
			result.setStatus(1);
			result.setMessage(e.getMessage());
			return result;
		}
	}
	
	private TLoanRepayment createRepayment(Long companyId, Long loanId, int type, int payType, int payMoney, int latefee) throws Exception{
		// 产生一条还款记录（初始状态）
		TLoanRepayment loanRepayment = new TLoanRepayment();
		loanRepayment.setCompanyId(CommonUtil.getLongValue(companyId));
		loanRepayment.setLoanId(loanId);
		loanRepayment.setType(type);
		loanRepayment.setPayType(payType);
		loanRepayment.setPayMoney(payMoney);
		loanRepayment.setLatefee(latefee);
		loanRepayment.setCreateTime(new Date());
		loanRepayment.setPayStatus(0);
		return loanRePayMentService.save(loanRepayment);
	}
	
	private Map<String,Object> getParams(TLoanRepayment loanRepayment, InterDtoCUser cust, Long companyId, int payMoney, int handleFee){
		// 组合支付需要的参数集
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("repayId", loanRepayment.getId());
		params.put("payMoney", ConstantsUtil.DEBUG_MODE==1 ? (1):payMoney);
		params.put("custId", cust.getCustId());
		params.put("custName", cust.getCustName());
		params.put("custIdNumber", cust.getCustNumber());
		params.put("phone", cust.getPhoneNo());
		params.put("companyId",companyId);
		params.put("customerId",cust.getCustId());
		return params;
	}
}
